<!-- src/components/MapScenicView.vue -->
<template>
  <div id="map-container" ref="mapContainer" style="width: 100%; height: 500px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"></div>
</template>

<script>
import { loadAMapScript } from '@/utils/amap-loader';
import { getScenicSpots } from '@/api/scenicSpots';

// 替换为你的高德 Key（在高德开放平台申请）
const AMAP_KEY = '66dc7b43fc69dbdafcf288e1e44ac144'; // ⬅️ 修改这里！

export default {
  name: 'MapScenicView',
  async mounted() {
    await this.initMap();
  },
  methods: {
    async initMap() {
      try {
        // 1. 加载高德地图 SDK
        await loadAMapScript(AMAP_KEY);

        // 2. 初始化地图（以福州市中心为视角）
        const map = new AMap.Map(this.$refs.mapContainer, {
          zoom: 13,
          center: [119.306239, 26.075302], // 福州市政府坐标
          viewMode: '2D',
          mapStyle: 'amap://styles/light' // 可选样式：'normal', 'dark', 'light'
        });

        // 3. 获取景点数据
        const spots = await getScenicSpots();

        // 4. 为每个景点添加标注
        spots.forEach(spot => {
          const position = new AMap.LngLat(spot.lng, spot.lat);

          const marker = new AMap.Marker({
            position,
            map,
            icon: new AMap.Icon({
              size: new AMap.Size(32, 32),
              image: '/icons/scenic-marker.png' // 图标路径（确保 public/icons/ 下有此文件）
            }),
            title: spot.name
          });

          // 5. 点击标注弹出信息窗
          const infoWindow = new AMap.InfoWindow({
            content: `
              <div style="padding: 12px; max-width: 220px;">
                <h4 style="margin: 0 0 8px 0; font-size: 16px;">${spot.name}</h4>
                <p style="margin: 0 0 12px 0; color: #666; font-size: 14px;">点击进入预约</p>
                <button 
                  onclick="location.href='/reserve?spot=${encodeURIComponent(spot.name)}'" 
                  style="padding: 6px 12px; background: #00A0E9; color: white; border: none; border-radius: 4px; cursor: pointer;">
                  立即预约
                </button>
              </div>`,
            offset: new AMap.Pixel(0, -36)
          });

          marker.on('click', () => {
            infoWindow.open(map, position);
          });
        });

        // 可选：添加比例尺插件
        AMap.plugin('AMap.Scale', () => {
          map.addControl(new AMap.Scale());
        });

      } catch (err) {
        console.error('地图初始化失败:', err);
        alert('地图加载失败，请刷新重试');
      }
    }
  }
};
</script>

<style scoped>
#map-container {
  background: #f0f0f0;
}
</style>